#include <vcl.h>
#include <math.h>

#include <io.h>
#include <utilcls.h>
#pragma hdrstop

#include "uEtat.h"
#include "uVisualise.h"
#include "Printer.h"
#include "uAbout.h"
#include "uFncGdi.h"
#include "uSelPrinter.h"
#include "uParametrages.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma link "CEditNum"
#pragma link "CEdit"
#pragma link "cedit"
#pragma link "ceditnum"
#pragma link "CEditUpDown"
#pragma resource "*.dfm"
#define ZOOM_DEB    30
#define ZOOM_DECAL  10
#define ZOOM_FIN   200

#define NB_DOC_MAX_SANS_FERMER 10
#define MODULE_TAG MODULE_TAG_VISUALISE
//#define RESOL_EMF    1440
typedef struct
{
    TDocument* Doc;
    TEtat* Etat;
    TList  *LstOfPages;
    int FirstPage;
//    PAGE* __fastcall GetPage(int nNPage);
}CARAC_DOCUMENT;
/*PAGE* __fastcall ETAT::GetPage( int nPage)
{
    int n = 0;
    for( int i = 0; i < LstOfPages->Count && n != nPage; i++)
    {

    }
    PAGE *p = PageAutreEtat, *pDernPage = this;
    int Niv = 0;
    while( p)
    {
        Niv++;
        pDernPage = p;
        p = p->PageAutreEtat;
    }
    *pnNiveau = Niv;
    return pDernPage;
} */

__fastcall PAGE::PAGE()
{
    LstCpCalcCol      = NULL;
    LstCpExtensibles  = NULL;
    LstCpEnCours      = NULL;
    Bookmark = 0;
    wTypeFirstBande = (TYPE_BANDE)0;
    wNiveauFirstBande = 0;
    AutreEtat = NULL;
    PageAutreEtat = NULL;
    EMFCanvas = NULL;
    ReportFinPageAffiche = false;
}

__fastcall PAGE::~PAGE( )
{
    if( LstCpCalcCol)       delete LstCpCalcCol;
    if( LstCpExtensibles)   delete LstCpExtensibles;
    if( LstCpEnCours)       delete LstCpEnCours;
    if( AutreEtat)
    {
//        if( AutreEtat->BaseDeDonnee && PageAutreEtat->Bookmark)
//            AutreEtat->BaseDeDonnee->FreeBookmark(PageAutreEtat->Bookmark);
        if( PageAutreEtat)
            delete PageAutreEtat;
    }
    if( EMFCanvas)        delete EMFCanvas;
    if( !EMFFile.IsEmpty()) ::DeleteFile( EMFFile.c_str());
}
PAGE* __fastcall PAGE::GetPageAAfficher(int *pnNiveau, TEtat* &e)
{
    PAGE *p = PageAutreEtat, *pDernPage = this;
    int Niv = 0;
    e = NULL;
    while( p)
    {
        Niv++;
        pDernPage = p;
        if( p->PageAutreEtat) e = p->AutreEtat;
        p = p->PageAutreEtat;
    }
    *pnNiveau = Niv;
    return pDernPage;
}



TFrmVisualise* __fastcall NewTFrmVisualise( TComponent* DocOwner, const AnsiString &SessionName)
{
    try{
        TFrmVisualise* f = new TFrmVisualise( DocOwner);
        if( Application && Application->MainForm && Application->MainForm->Handle)
            ::SetWindowLong( f->Handle, GWL_HWNDPARENT, (long)Application->MainForm->Handle);
        if( dynamic_cast<TComponent*>(DocOwner))
            ((TComponent*)DocOwner)->RemoveComponent(f);
        Glob->SessionName = SessionName;
        return f;
    }CATCH_EXCEPTION( TAG( 0))
    return NULL;
}
void __fastcall DeleteTFrmVisualise(TFrmVisualise* form )
{
    if( form)
        delete form;
}


bool __fastcall TFrmVisualise::OnDebutDocEvent(   TDocument  *Doc)
{
    try{
        return( f_OnDebutDoc? f_OnDebutDoc( Doc) : true);
    }CATCH_EXCEPTION( TAG( 1))
    return true;
}

//---------------------------------------------------------------------------
bool __fastcall TFrmVisualise::OnFinDocEvent(   TDocument  *Doc)
{
    try{
        return( f_OnFinDoc? f_OnFinDoc( Doc) : true);
    }CATCH_EXCEPTION( TAG( 2))
    return true;
}

//---------------------------------------------------------------------------
#define IS_EVENEMENT( Etat, fnEvenement) ( ((Etat->TakeEvForces && Etat->##fnEvenement##Force) || f_##fnEvenement)? true : false)
#define APPEL_EV( Etat, fnEvenement, Param, RetourSiRien) ( Etat->TakeEvForces? (Etat->##fnEvenement##Force ? Etat->##fnEvenement##Force( Param): RetourSiRien)  \
                                                                              : (f_##fnEvenement            ? f_##fnEvenement( Param)           : RetourSiRien) )
#define APPEL_EV_2( Etat, fnEvenement, Param1, Param2, RetourSiRien) ( Etat->TakeEvForces? (Etat->##fnEvenement##Force ? Etat->##fnEvenement##Force( Param1, Param2): RetourSiRien)  \
                                                                                         : (f_##fnEvenement            ? f_##fnEvenement( Param1, Param2)           : RetourSiRien) )
#define APPEL_EV_4( Etat, fnEvenement, Param1, Param2, Param3, Param4, RetourSiRien) ( Etat->TakeEvForces? (Etat->##fnEvenement##Force ? Etat->##fnEvenement##Force( Param1, Param2, Param3, Param4): RetourSiRien)  \
                                                                                                       : (f_##fnEvenement            ? f_##fnEvenement( Param1, Param2, Param3, Param4)           : RetourSiRien) )
#define APPEL_EV2( Etat, fnEvenement, Param) if( Etat->TakeEvForces) { if( Etat->##fnEvenement##Force) Etat->##fnEvenement##Force( Param); }  \
                                                                else { if( f_##fnEvenement           ) f_##fnEvenement( Param);            }
#define APPEL_EV2_2( Etat, fnEvenement, Param1, Param2) if( Etat->TakeEvForces) { if( Etat->##fnEvenement##Force) Etat->##fnEvenement##Force( Param1, Param2); }  \
                                                                         else { if( f_##fnEvenement           ) f_##fnEvenement( Param1, Param2);            }
bool __fastcall TFrmVisualise::OnSQLParamsEvent(   TEtat  *Etat, TParams *SQLParam)
{
    try{
        bool bReturn;
        bReturn = APPEL_EV_2( Etat, OnSQLParams, Etat, SQLParam, true);
        //bReturn = ( f_OnSQLParams? f_OnSQLParams( Etat) : true);
        int nIndice = CbDocument->Items->IndexOfObject( Etat);
        if( nIndice != -1)
            CbDocument->Items->Strings[nIndice] = Etat->Titre;
        return bReturn;
    }CATCH_EXCEPTION( TAG( 3))
    return true;
}

//---------------------------------------------------------------------------
bool __fastcall TFrmVisualise::OnBDInitializedEvent( TEtat *Etat)
{
    try{
        return APPEL_EV( Etat, OnBDInitialized, Etat, true);
/*        if( f_OnBDInitialized)
            return f_OnBDInitialized( Etat);*/
    }CATCH_EXCEPTION( TAGL)
    return true;
}

//---------------------------------------------------------------------------
bool __fastcall TFrmVisualise::OnDebutEtatEvent(   TEtat  *Etat)
{
    try{
        bool bReturn;
        if( !IS_EVENEMENT(Etat, OnDebutEtat)/*f_OnDebutEtat*/)   Etat->NbCopies = 1;

        //if( m_NbCopies)  Etat->NbCopies = m_NbCopies;

        bReturn = APPEL_EV( Etat, OnDebutEtat, Etat, true && Etat->NbCopies);
//        bReturn = (f_OnDebutEtat? f_OnDebutEtat( Etat) : true && Etat->NbCopies);

        int nIndice = CbDocument->Items->IndexOfObject( Etat);
        if( nIndice != -1)
            CbDocument->Items->Strings[nIndice] = Etat->Titre;
        return bReturn;
    }CATCH_EXCEPTION( TAG( 4))
    return true;
}

//---------------------------------------------------------------------------
bool __fastcall TFrmVisualise::OnFinEtatEvent(   TEtat  *Etat)
{
    try{
        bool bReturn;
        bReturn = APPEL_EV( Etat, OnFinEtat, Etat, true);
//        bReturn = ( f_OnFinEtat? f_OnFinEtat( Etat) : true);
        int nIndice = CbDocument->Items->IndexOfObject( Etat);
        if( nIndice != -1)
            CbDocument->Items->Strings[nIndice] = Etat->Titre;
        return bReturn;
    }CATCH_EXCEPTION( TAG( 5))
    return true;
}

//---------------------------------------------------------------------------
bool __fastcall TFrmVisualise::OnFirstBandeEtatEvent(   TBande  *Bande)
{
    try{
        return APPEL_EV( Bande->EtatOwner, OnFirstBandeEtat, Bande, true);
//        return( f_OnFirstBandeEtat? f_OnFirstBandeEtat( Bande) : true);
    }CATCH_EXCEPTION( TAG( 6))
    return true;
}

//---------------------------------------------------------------------------
bool __fastcall TFrmVisualise::OnBandeEvent(   TBande  *Bande)
{
    try{
        if( ((Bande->Type == e_EnTete) || (Bande->Type == e_Pied)) &&
             Bande->OwnerDocument)
            return f_OnBande? f_OnBande( Bande): true;
        else
            return APPEL_EV( Bande->EtatOwner, OnBande, Bande, true);
//        return( f_OnBande? f_OnBande( Bande) : true);
    }CATCH_EXCEPTION( TAG( 6))
    return true;
}

//---------------------------------------------------------------------------
void __fastcall TFrmVisualise::OnAfterFirstBandeInitEvent( const TBande  *Bande)
{
    try{
      /*  if( ((Bande->Type == e_EnTete) || (Bande->Type == e_Pied)) &&
             Bande->OwnerDocument)
        {
            if(f_OnAfterFirstBandeInit) f_OnAfterFirstBandeInit( Bande);
        }else */
        {
            APPEL_EV2( Bande->EtatOwner, OnAfterFirstBandeInit, Bande);
/*            if( Bande->EtatOwner->TakeEvForces)
            {
                if(Bande->EtatOwner->OnAfterFirstBandeInitForce) Bande->EtatOwner->OnAfterFirstBandeInitForce( Bande);
            }else
            {
                if(f_OnAfterFirstBandeInit) f_OnAfterFirstBandeInit( Bande);
            }*/
//            APPEL_EV( Bande->EtatOwner, OnAfterFirstBandeInit, Bande, true);
        }
//        return( f_OnBande? f_OnBande( Bande) : true);
    }CATCH_EXCEPTION( TAG( 6))
}

//---------------------------------------------------------------------------
bool __fastcall TFrmVisualise::OnChampEvent(   TCpChamp  *Champ)
{
    bool b = true;
    try{
        if( ((Champ->BandeOwner->Type == e_EnTete) || (Champ->BandeOwner->Type == e_Pied)) &&
             Champ->BandeOwner->OwnerDocument)
            b = f_OnChamp? f_OnChamp( Champ): true;
        else
            b = APPEL_EV( Champ->EtatOwner, OnChamp, Champ, true);
//        b = ( f_OnChamp? f_OnChamp( Champ) : true);
    }CATCH_EXCEPTION( TAG( 7))
    return b;
}

//---------------------------------------------------------------------------
bool __fastcall TFrmVisualise::OnTableauEvent(   TCpTableau  *Tableau)
{
    bool b = true;
    try{
        if( ((Tableau->BandeOwner->Type == e_EnTete) || (Tableau->BandeOwner->Type == e_Pied)) &&
             Tableau->BandeOwner->OwnerDocument)
            b = f_OnTableau? f_OnTableau( Tableau): true;
        else
            b = APPEL_EV( Tableau->EtatOwner, OnTableau, Tableau, true);
//        return( f_OnTableau? f_OnTableau( Tableau) : true);
    }CATCH_EXCEPTION( TAG( 8))
    return b;
}
void __fastcall TFrmVisualise::OnErrorEvent( const TObject *o, const AnsiString &Message)
{
    try{
        const TCpChamp *CpChampEnCours = dynamic_cast<const TCpChamp *>(o);
        const TBande   *BandeEnCours   = dynamic_cast<const TBande *>(o);
        if( f_OnError)
        {
            const TBande   *Bd = CpChampEnCours? CpChampEnCours->BandeOwner : BandeEnCours;
            const TEtat    *e  = Bd? Bd->EtatOwner : dynamic_cast<const TEtat *>(o);
            if( ((Bd->Type == e_EnTete) || (Bd->Type == e_Pied)) && Bd->OwnerDocument)
            {
                if( f_OnError) f_OnError( o, Message);
            }else
                APPEL_EV2_2( e, OnError, o, Message);
        }else
        {
            AnsiString s;
            if( CpChampEnCours)
                s = AnsiString( "Erreur :\nChamp : ") +  CpChampEnCours->Nom + "\n" + Message;
            else if( BandeEnCours)
                s = AnsiString( "Erreur :\nBande : ") +  BandeEnCours->Titre + "\n" + Message;
            else s = Message;
            EICErreur( s);
        }
    }CATCH_EXCEPTION( TAG( 9))
}
bool __fastcall TFrmVisualise::OnVariableEvent(const TObject *o, const AnsiString &Variable, TFieldType &Type, AnsiString &Valeur)
{
    bool b = false;
    try{
        const TCpChamp *CpChampEnCours = dynamic_cast<const TCpChamp *>(o);
        const TBande   *BandeEnCours   = dynamic_cast<const TBande *>(o);
        if( f_OnError)
        {
            const TBande   *Bd = CpChampEnCours? CpChampEnCours->BandeOwner : BandeEnCours;
            const TEtat    *e  = Bd? Bd->EtatOwner : dynamic_cast<const TEtat *>(o);
            if( ((Bd->Type == e_EnTete) || (Bd->Type == e_Pied)) && Bd->OwnerDocument)
            {
                if( f_OnVariable) b = f_OnVariable( o, Variable, Type, Valeur);
            }else
                b = APPEL_EV_4( e, OnVariable, o, Variable, Type, Valeur, b);
        }
    }CATCH_EXCEPTION( TAG( 10))
    return b;
}
//---------------------------------------------------------------------------

/*TEtat* __fastcall TFrmVisualise::OnGetEtatEnDessousEvent( TEtat *Etat)
{
    try{
        if( Etat->NumeroEnVisu < m_LstDocument->Count -1)
        {
            ETAT *e = (ETAT*)m_LstDocument->Items[ Etat->NumeroEnVisu+1];
            if( e->Etat->DebPage == Deb_SuitePrec)
            {
                if( e->Etat->Portrait != Etat->Portrait)
                {
                    ShowMessage( AnsiString("Il est impossible d'éditer l'état \"") + e->Etat->Titre +
                                 "\" à la suite de l'état \"" + Etat->Titre +
                                 "\" car ils n'ont pas la même orientation.");
                    return NULL;
                }
                return e->Etat;
//                Etat->DrawEtatSuivant( e->Etat);
            }
        }
    }CATCH_EXCEPTION( TAG( 9))
    return NULL;
} */

//---------------------------------------------------------------------------
void __fastcall TFrmVisualise::SubClassWndProcCbDocument(Messages::TMessage &Message)
{
  try{
    switch( Message.Msg)
    {
        case WM_KEYDOWN:
            if( CbDocument && !CbDocument->DroppedDown)
            {
                unsigned short Key = (short)Message.WParam;
                switch( Message.WParam)
                {
                    case VK_NEXT:
                    case VK_PRIOR: //return ;
                    case VK_UP:
                    case VK_DOWN:
                    case VK_LEFT:
                    case VK_RIGHT:
                    case VK_END:
                    case VK_HOME: return( FormKeyDown( this, Key, TShiftState()));
                }
            }break;
    }
  }CATCH_EXCEPTION( TAGL)

  try{
    if( m_OldWindowProcCbDocument) m_OldWindowProcCbDocument(Message);
  }CATCH_EXCEPTION( TAGL)
}

//---------------------------------------------------------------------------
void __fastcall TFrmVisualise::SubClassWndProccbZoom(Messages::TMessage &Message)
{
  try{
    if( (Message.Msg == WM_KEYDOWN) && cbZoom && !cbZoom->DroppedDown)
    {
        unsigned short Key = (short)Message.WParam;
        switch( Message.WParam)
        {
            case VK_NEXT:
            case VK_PRIOR: // return;
            case VK_UP:
            case VK_DOWN:
            case VK_LEFT:
            case VK_RIGHT:
            case VK_END:
            case VK_HOME: return( FormKeyDown( this, Key, TShiftState()));
        }
    }
    if( m_OldWindowProccbZoom) m_OldWindowProccbZoom(Message);
  }CATCH_EXCEPTION( TAGL)
}

//---------------------------------------------------------------------------
#include <jpeg.hpp>
__fastcall TFrmVisualise::TFrmVisualise(TComponent* DocOwner)
    : TForm(DocOwner)
{
    try{
ActMail->Visible = false;

        m_bGEDEICInstalle = GED_IsInstallee();
        m_Drag.y = -1;
        m_Drag.x = -1;
        if( !GED_gGestionEnvoi)
        {
          ToolGED->Visible  = false;
          ActGED->ShortCut = 0;
          StVisu->Panels->Delete( 2);
        }


        m_PDFInactif = false;
        m_bConceptionBefore = Glob->bConception;
        Glob->bConception = false;
        m_ShowNbCopies = true;
        for( int i = ZOOM_DEB; i <= ZOOM_FIN; i+=ZOOM_DECAL)
            cbZoom->Items->AddObject( AnsiString( (int)i)+" %", (TObject*)i);
        ImVisu->Picture->Graphic = new Graphics::TBitmap();
        m_OldResolution = MAKELONG( Glob->ResolutionX, Glob->ResolutionY);

/*        m_ImpressionFaite = false;
        cbZoom->ItemIndex = (100 - ZOOM_DEB) / 10;*/

        m_OldWindowProcCbDocument = CbDocument->WindowProc;
        CbDocument->WindowProc = SubClassWndProcCbDocument;
        m_OldWindowProccbZoom = cbZoom->WindowProc;
        cbZoom->WindowProc = SubClassWndProccbZoom;
        m_CbDocumentTenirCompteDuProchainDestroy = true;
        
       etatPrec = NULL;
       m_bPrintOnly = true;
       m_OldResol = 0;
    }CATCH_EXCEPTION( TAG(10))
}
//---------------------------------------------------------------------------
void __fastcall TFrmVisualise::FreeAllPages(int n)
{
  try{
    etatPrec = NULL;
    TEtat *Etat;
    for( int i=(n==-1)?0:n; i < ((n==-1)?CbDocument->Items->Count:n+1); i++)
    {
        CARAC_DOCUMENT* CaracDoc = (CARAC_DOCUMENT*)CbDocument->Items->Objects[ i];
        for( Etat = CaracDoc->Etat; Etat; Etat = Etat->EtatSuivant)
            Etat->UnInitialize();
    }
    while( (n==-1)?CbDocument->Items->Count:true)
    {
        CARAC_DOCUMENT* CaracDoc = (CARAC_DOCUMENT*)CbDocument->Items->Objects[ (n==-1)?0:n];
        CbDocument->Items->Delete((n==-1)?0:n);
        for( int j = 0; j < CaracDoc->LstOfPages->Count; j++)
        {
            PAGE* p = (PAGE*)CaracDoc->LstOfPages->Items[ j];
            if( CaracDoc->Etat->BaseDeDonnee)
                CaracDoc->Etat->BaseDeDonnee->FreeBookmark(p->Bookmark);
            delete p;
        }
        delete CaracDoc->LstOfPages;
        if( n==-1)
        {
            for( Etat = CaracDoc->Etat; Etat; Etat = Etat->EtatSuivant)
            {
                Deconnecte( Etat->DocOwner);
            }
        }
        if( CaracDoc->Doc)
        {
            Deconnecte( CaracDoc->Doc);
            delete CaracDoc->Doc;
        }
        delete CaracDoc;
        if( n!=-1) break;
    }
  }CATCH_EXCEPTION( TAGL)
}
__fastcall TFrmVisualise::~TFrmVisualise()
{
    try{
        CbDocument->WindowProc = m_OldWindowProcCbDocument;
        cbZoom->WindowProc = m_OldWindowProccbZoom;
        FreeAllPages();
//        Glob->Resolution = m_OldResolution;
        Glob->bConception = m_bConceptionBefore;
    /*    delete (Graphics::TBitmap*)ImVisu->Picture->Graphic;
        ImVisu->Picture->Graphic = NULL;*/
        Glob->ResolutionX = Glob->ResolutionY = Glob->ResolEcran;  
    }CATCH_EXCEPTION( TAG(11))
}
//---------------------------------------------------------------------------
int __fastcall TFrmVisualise::ShowModal(void)
{
    m_bAnnulee = false;
    m_ImpressionFaite = false;
    m_bPrintOnly = false;
    cbZoom->ItemIndex = (100 - ZOOM_DEB) / 10;
    if( CbDocument->Items->Count)
    {
        edPage->Max = 9999;
        CbDocument->ItemIndex = 0;//min( CbDocument->Items->Count-1, nPageCourante);
        Tag = 1;
        CbDocumentChange( NULL);
        Tag = 0;
    }
    if( !Glob->LanceEnConception)
    {
/*        SepLangue->Parent = this;
        edLangue->Parent = this;
        lblLangue->Parent = this;*/
    }else{
        SepLangue->Visible = true;
        edLangue->Visible = true;
        lblLangue->Visible = true;
    }
    int bReturn = inherited::ShowModal();
    m_bPrintOnly = true;
    return bReturn;
}

//---------------------------------------------------------------------------
void __fastcall TFrmVisualise::Ajoute( TDocument* Doc, int nPageCourante)
{
    try{
/*        Doc->OnDebutDoc    = OnDebutDocEvent;
        if( Doc->AImprimer())
        {*/
            Connecte( Doc);
            for( short i = 0; i < Doc->NbEtats; i++)
            {
                Ajoute( Doc->GetEtat( i), true, 0);
            }
        /*}else
            Doc->OnDebutDoc    = OnDebutDocEvent;*/

    }CATCH_EXCEPTIONc( TAG( 12),
    {
        m_bAnnulee = true;
        Close();
    })
}
//---------------------------------------------------------------------------
TEtat* __fastcall TFrmVisualise::Ajoute( TEtat* Etat, bool bWithDocOrigin, unsigned long Tag)
{
    try{
        CARAC_DOCUMENT *CaracDoc = new CARAC_DOCUMENT;
        if( !bWithDocOrigin)
        {
            CaracDoc->Doc = new TDocument( EmptyStr);
            CaracDoc->Doc->Assign( Etat->DocOwner);
            CaracDoc->Doc->Titre = Etat->DocOwner->Titre;
            CaracDoc->Etat = CaracDoc->Doc->AjouteEtat( Etat, Tag);
            Connecte( CaracDoc->Doc);
        }else{
            CaracDoc->Doc = NULL;
            CaracDoc->Etat = Etat;
        }
        if( CaracDoc->Etat->AImprimer())
        {
            if( (CaracDoc->Etat->DebPage == Deb_AutreDocument) || !etatPrec)
            {
                CaracDoc->Etat->DocOwner->OnDebutDoc    = OnDebutDocEvent;
                CaracDoc->Etat->DocOwner->AImprimer();
                CaracDoc->Etat->DocOwner->OnDebutDoc    = NULL;
                CaracDoc->LstOfPages = new TList();
                CaracDoc->FirstPage = 1;

                CaracDoc->Etat->NumeroEnVisu = CbDocument->Items->AddObject( CaracDoc->Etat->Titre, (TObject*)CaracDoc);
                if( CbDocument->Items->Count == 1) Caption = CaracDoc->Etat->Titre;
                else                               Caption = "Visualisation";
                etatPrec = CaracDoc->Etat;
            }else{
                TEtat *sEtat;
                CARAC_DOCUMENT *CaracDocPrec = (CARAC_DOCUMENT*)CbDocument->Items->Objects[ etatPrec->NumeroEnVisu];

                if( !bWithDocOrigin)
                {
//                    sEtat = CaracDoc->Doc->GetEtat( Etat->Titre);
//                    if( !sEtat)
                      sEtat = CaracDocPrec->Doc->AjouteEtat( CaracDoc->Etat, Tag);
                }else
                    sEtat = Etat;

                if( CaracDoc->Doc)
                {
                    Deconnecte( CaracDoc->Doc);
                    delete CaracDoc->Doc;
                }
                delete CaracDoc;
                etatPrec->EtatSuivant = sEtat;
                sEtat->NumeroEnVisu = etatPrec->NumeroEnVisu;
                etatPrec = sEtat;
            }
            if( (etatPrec->NumeroEnVisu > NB_DOC_MAX_SANS_FERMER) && etatPrec->BaseDeDonnee)
                etatPrec->BaseDeDonnee->Close();

        }else
        {
            if( CaracDoc->Doc) delete CaracDoc->Doc;
            delete CaracDoc;
        }
    }CATCH_EXCEPTION( TAG(13))
    return etatPrec;
}
void __fastcall TFrmVisualise::Connecte( TDocument* Doc)
{
    Doc->OnFinPage          = FinPageEvent;
    Doc->OnDebutPage        = DebutPageEvent;
    Doc->OnDebutDoc         = OnDebutDocEvent;
    Doc->OnFinDoc           = OnFinDocEvent;
    Doc->OnDebutEtat        = OnDebutEtatEvent;
    Doc->OnSQLParams        = OnSQLParamsEvent;
    Doc->OnBDInitialized    = OnBDInitializedEvent;
    Doc->OnFinEtat          = OnFinEtatEvent;
    Doc->OnFirstBandeEtat   = OnFirstBandeEtatEvent;
    Doc->OnBande            = OnBandeEvent;
    Doc->OnAfterFirstBandeInit   = OnAfterFirstBandeInitEvent;
    Doc->OnChamp            = OnChampEvent;
    Doc->OnTableau          = OnTableauEvent;
    Doc->OnError            = OnErrorEvent;
    Doc->OnVariable         = OnVariableEvent;
    Doc->Langue             = edLangue->Position;
}
void __fastcall TFrmVisualise::Deconnecte( TDocument* Doc)
{
    Doc->OnDebutPage        = NULL;
    Doc->OnDebutDoc         = NULL;
    Doc->OnFinDoc           = NULL;
    Doc->OnDebutEtat        = NULL;
    Doc->OnSQLParams        = NULL;
    Doc->OnBDInitialized    = NULL;
    Doc->OnFinEtat          = NULL;
    Doc->OnFirstBandeEtat   = NULL;
    Doc->OnBande            = NULL;
    Doc->OnAfterFirstBandeInit   = NULL;
    Doc->OnChamp            = NULL;
    Doc->OnTableau          = NULL;
    Doc->OnError            = NULL;
    Doc->OnVariable         = NULL;
}

//---------------------------------------------------------------------------
void __fastcall TFrmVisualise::RecupereDebutPage( const TEtat *Etat, const TBande *FirstOnNewPage, PAGE* p, bool EtatPlusHautNiveau)
{
    try{
        if( EtatPlusHautNiveau || !Etat->EtatAppelant || (Etat->EtatAppelant->EtatSuivant != Etat))
        {
            if( Etat->BaseDeDonnee)
            {
//                if( Etat->EtatAppelant)
                    p->Bookmark = (void*)Etat->BaseDeDonnee->RecNo;
//                else
//                    p->Bookmark = Etat->BaseDeDonnee->GetBookmark();
            }
            p->wTypeFirstBande   = FirstOnNewPage->Type;
            if( FirstOnNewPage->Type > e_Utilisateur)
            {
                p->NiveauTypeBandeAvUtil = Etat->NiveauTypeBeforeUtil;
                p->NiveauTypeBandeApUtil = Etat->NiveauTypeAfterUtil;
            }
            if( GET_TYPBANDE(p->NiveauTypeBandeApUtil) == e_Principal)
            {
                p->bAutoLoop              =  Etat->GetBandeDetail()->bAutoLoop;
                p->IndiceRepetitionBande  =  Etat->GetBandeDetail()->IndiceRepetition;
            }else
                p->IndiceRepetitionBande = Etat->BandeEnCours->IndiceRepetition;
            p->wNiveauFirstBande = FirstOnNewPage->Niveau;
        // ATTENTION SI ON STOCKE + D'INFOS VERIFIER QUE LES COMPOSANTS SOIENT BIEN INITIALISES LORS DE TListOfComposants::Draw EN
        // CALCUL DE PAGE
            p->LstCpCalcCol = new TStringList();
            for( int i = 0; i < Etat->LstCpChamp->Count; i++)
            {
                TCpChamp* CpChamp = (TCpChamp*)Etat->LstCpChamp->Items[i];
                if( (CpChamp->Type == tc_Calcule) && (CpChamp->TypeCalcul == tcalc_Info)) continue;
                bool bInit = (((CpChamp->Type==tc_BaseDeDonnee) || ((CpChamp->Type==tc_Calcule)&&(CpChamp->TypeCalcul==tcalc_Ligne)))&& Etat->ReinitBDDApresCalculsPage)? false:CpChamp->Initialise;
                p->LstCpCalcCol->AddObject( CpChamp->AllTextes,
                                            (TObject*)bInit);
            }
            p->LstCpExtensibles = new TList();
            for( int i = 0; i < Etat->LstCpExtensibles->Count; i++)
                p->LstCpExtensibles->Add( (void*)((TCpTexte*)Etat->LstCpExtensibles->Items[i])->nLastCharPrint );

            p->LstCpEnCours = new TList();
            for( int i = 0; i < Etat->LstCpEnCours->Count; i++)
                p->LstCpEnCours->Add( Etat->LstCpEnCours->Items[i]);

        }
        p->ReportFinPageAffiche  = Etat->ReportFinPageAffiche;
    }CATCH_EXCEPTION( TAG( 101))
}
void __fastcall TFrmVisualise::InitialiseDebutPage( const TEtat *Etat, PAGE* p)
{
    try {
        if( Etat->BaseDeDonnee)
        {
            TDataChangeEvent eDtCh = Etat->DataSource->OnDataChange;
            Etat->DataSource->OnDataChange = NULL;
//            if( Etat->EtatAppelant)
            if( Etat->BasDerniereBande != -2) 
                Etat->BaseDeDonnee->RecNo = (int)p->Bookmark;
//            else
//                Etat->BaseDeDonnee->GotoBookmark( p->Bookmark);
            Etat->DataSource->OnDataChange = eDtCh;

            TBande *b = Etat->LstBandes->SearchBande( e_Principal);
            while( b->LstBandes)
            {
                if( b->LstBandes->bRuptureVisible && b->FieldRupture)
                    b->ValeurChpRupture = b->FieldRupture->AsString;
                b = b->LstBandes->SearchBande( e_Principal);
            }
        }
        if(p->LstCpCalcCol)
        {
            for( int i = 0, j=0; i < Etat->LstCpChamp->Count; i++)
            {
                TCpChamp* CpChamp = (TCpChamp*)Etat->LstCpChamp->Items[i];
                if( (CpChamp->Type == tc_Calcule) && (CpChamp->TypeCalcul == tcalc_Info)) continue;
                CpChamp->AllTextes = p->LstCpCalcCol->Strings[j];
                CpChamp->Initialise = (bool)(p->LstCpCalcCol->Objects[j]);
                j++;
            }
        }
        if(p->LstCpExtensibles)
        {
            for( int i = 0; i < Etat->LstCpExtensibles->Count; i++)
                ((TCpTexte*)Etat->LstCpExtensibles->Items[i])->nLastCharPrint = (int)p->LstCpExtensibles->Items[i];
        }
        Etat->LstCpEnCours->Clear();
        if(p->LstCpEnCours)
        {
            for( int i = 0; i < p->LstCpEnCours->Count; i++)
                Etat->LstCpEnCours->Add( p->LstCpEnCours->Items[i]);
        }
        if(Etat->BandeEnCours)
           Etat->BandeEnCours->IndiceRepetition = p->IndiceRepetitionBande;
        if( GET_TYPBANDE( p->NiveauTypeBandeApUtil) == e_Principal)
            Etat->GetBandeDetail()->bAutoLoop = p->bAutoLoop;
    }CATCH_EXCEPTION( TAG( 102))
}
//---------------------------------------------------------------------------
bool __fastcall TFrmVisualise::AfficheEMF( const TEtat* Etat, PAGE *p)
{
    HENHMETAFILE hemf;
    TCanvas * c=NULL;
    if( p->EMFCanvas)
    {
        hemf = ::_CloseEnhMetaFile( TAGL, p->EMFCanvas->Handle);
        delete p->EMFCanvas;
        p->EMFCanvas = NULL;
        Glob->ResolutionX = LOWORD( m_OldResol);
        Glob->ResolutionY = HIWORD( m_OldResol);
        m_OldResol = 0;
        Glob->EICPrinter = m_OldPrinter;
        Etat->DocOwner->ChangeSupport( m_OldSupport);

        c = Etat->DocOwner->IsCanvasSupport();
    }else{
        c = Etat->DocOwner->IsCanvasSupport();
        if( !c) return false;
        hemf = ::_GetEnhMetaFile( TAGL, p->EMFFile.c_str());
    }
    RECT r ={0,0,Etat->Largeur.PixelsX, Etat->Hauteur.PixelsY};
    if( c) ::_PlayEnhMetaFile( TAGL, c->Handle, hemf, &r);
    ::_DeleteEnhMetaFile(TAGL, hemf);
    return true;
}

void __fastcall TFrmVisualise::FinPageEvent(TObject* Sender)
{
  #ifdef RESOL_EMF
    TEtat    *Etat = (TEtat*)Sender;
    CARAC_DOCUMENT* CaracDoc = (CARAC_DOCUMENT*)CbDocument->Items->Objects[ Etat->NumeroEnVisu];
    PAGE *p = (PAGE*)CaracDoc->LstOfPages->Items[ Etat->CurrentPage -1];
    if( p->EMFCanvas)
    {
        AfficheEMF( Etat, p);
    }
  #endif
}

//---------------------------------------------------------------------------
void __fastcall TFrmVisualise::DebutPageEvent(TObject* Sender)
{

    try {
    TBande    *FirstOnNewPage = (TBande*)Sender;
    TEtat     *Etat = FirstOnNewPage->EtatOwner;
    CARAC_DOCUMENT* CaracDoc = (CARAC_DOCUMENT*)CbDocument->Items->Objects[ Etat->NumeroEnVisu];
  #ifdef RESOL_EMF
    if( Etat->DocOwner->Support == CanvasCALCUL_NB_PAGES)
        m_bPrintOnly = false;
  #endif
    if( !m_bPrintOnly)
    {
        PAGE *p = NULL;
        if( Etat->CurrentPage > CaracDoc->LstOfPages->Count)
        {
            TEtat* ce=Etat;
            TBande* b=FirstOnNewPage;
            p = new PAGE;

            do{
                RecupereDebutPage( ce, b, p, ce==Etat);
                if( ce->EtatAppelant)
                {
                    PAGE *p1 = p;
                    p = new PAGE;
                    p->AutreEtat = ce;
                    p->PageAutreEtat = p1;

                    ce = ce->EtatAppelant;
                    b = ce->BandeEnCours;
                }else ce = NULL;
            }while(ce);
    #ifdef RESOL_EMF
            if( Etat->ReinitBDDApresCalculsPage)
            {
                p->EMFFile.SetLength( MAX_PATH);
                ChkSDK( TAGL, ::GetTempFileName( Glob->szTempPath, "EICMF", 0, p->EMFFile.c_str()), 0);
                ::DeleteFile(p->EMFFile.c_str());
                p->EMFFile.SetLength( strlen( p->EMFFile.c_str()));
                p->EMFFile[p->EMFFile.Length()-2] = 'e';
                p->EMFFile[p->EMFFile.Length()] = 'f';
                p->EMFCanvas = new TCanvas();
                p->EMFCanvas->Handle = ::MyCreateEnhMetaFile( TAGL, Etat->Largeur, Etat->Hauteur,RESOL_EMF, p->EMFFile.c_str());
                m_OldResol = Glob->Resolution;
                Glob->Resolution = RESOL_EMF;
                m_OldPrinter = Glob->EICPrinter;
                Glob->EICPrinter = 0;
            }
    #endif
            CaracDoc->LstOfPages->Add( p);
        }else
        {
            bool bInit = true;
            if( IsPrinting())
            {
                switch( PrintDialog1->PrintRange)
                {
                    case prSelection :                                                          break;
                    case prAllPages  : bInit = false;                                           break;
                    case prPageNums  : bInit = (Etat->CurrentPage == PrintDialog1->FromPage);   break;
                }
            }
            if( bInit)
            {
                p = (PAGE*)CaracDoc->LstOfPages->Items[ Etat->CurrentPage -1];
        #ifdef RESOL_EMF
                if( p->EMFCanvas)
                {
        #endif
                    TEtat *ce = CaracDoc->Etat;
                    for( ; p != NULL;  ce = p->AutreEtat, p = p->PageAutreEtat)
                    {
                        InitialiseDebutPage( ce, p);
                        ce->ReportFinPageAffiche = p->ReportFinPageAffiche;
                    }
        #ifdef RESOL_EMF
                }
        #endif
            }
        }
    }

    if( Etat->DocOwner->Support != CanvasCALCUL_NB_PAGES)
    {
        TCanvas   *Support = CanvasIMPRIME_DS_VIDE;
        if( IsPrinting())
        {
            switch( PrintDialog1->PrintRange)
            {
                case prSelection :
                    if( Etat->CurrentPage == edPage->Valeur)
                        Support = Glob->EICPrinter->Canvas;
                    else if( Etat->CurrentPage > edPage->Valeur)
                        throw EAbort("Interruption");
                    break;
                case prAllPages  :
                    Support = Glob->EICPrinter->Canvas;
                    break;
                case prPageNums  :
                    if( (Etat->CurrentPage >= PrintDialog1->FromPage) &&
                        (Etat->CurrentPage <= PrintDialog1->ToPage  )   )
                        Support = Glob->EICPrinter->Canvas;
                    else if( Etat->CurrentPage > PrintDialog1->ToPage)
                        throw EAbort("Interruption");
                    break;
            }
        }
        else if( Etat->CurrentPage == edPage->Valeur)
        {
            InitPage(Etat);
            Support = ImVisu->Picture->Bitmap->Canvas;
        }else if( Etat->CurrentPage > edPage->Valeur)
            Support = CanvasIMPRIME_STOP;
        Etat->DocOwner->ChangeSupport( Support);
    }
  #ifdef RESOL_EMF
    PAGE *p = (PAGE*)CaracDoc->LstOfPages->Items[ Etat->CurrentPage -1];
    if( !p->EMFCanvas)
    {
        if( AfficheEMF( Etat, p))
            Etat->DocOwner->ChangeSupport( CanvasIMPRIME_DS_VIDE_EMF);
    }else{
        m_OldSupport = ((TCanvas*)Etat->DocOwner->Support);
        Etat->DocOwner->ChangeSupport( p->EMFCanvas);
    }
  #endif

    }catch(EAbort &e){throw;}
    CATCH_EXCEPTION( TAG( 14))
}


void __fastcall TFrmVisualise::CbDocumentChange(TObject *Sender)
{
    try{
        if( CbDocument->ItemIndex == -1) return;
        CARAC_DOCUMENT* CaracDoc;
        if( (CbDocument->Tag > NB_DOC_MAX_SANS_FERMER) && (CbDocument->Tag != CbDocument->ItemIndex))
        {
            CaracDoc = (CARAC_DOCUMENT*)CbDocument->Items->Objects[ CbDocument->Tag];
            for( TEtat *Etat = CaracDoc->Etat; Etat; Etat = Etat->EtatSuivant)
            {
                if( Etat->BaseDeDonnee) Etat->BaseDeDonnee->Close();
            }
        }

        CaracDoc = (CARAC_DOCUMENT*)CbDocument->Items->Objects[ CbDocument->ItemIndex];
        if( CaracDoc->Doc) edLangue->Max = CaracDoc->Doc->NbLangues-1;
        else edLangue->Max = CaracDoc->Etat->DocOwner->NbLangues-1;

        if( CaracDoc->Etat->NumberOfPage)
            edPage->Max = CaracDoc->Etat->NumberOfPage;
        CbDocument->Hint = CaracDoc->Etat->Titre;
        edPage->Tag = 1;
        edPage->Valeur = 1;
        cbZoomChange(NULL);

        CbDocument->Tag = CbDocument->ItemIndex;
        if( StVisu->Panels->Count > 2)
          StVisu->Panels->Items[2]->Text = "Classement GED : " + CaracDoc->Etat->GED_Criteres + "; Titre : " + CaracDoc->Etat->NomDocGED;
    /*    if( edPage->Valeur!=1) edPage->Valeur = 1;
        else                   edPageChange( Sender);*/
    }CATCH_EXCEPTION( TAG(15))
}
//---------------------------------------------------------------------------
void __fastcall TFrmVisualise::edPageChange(TObject *Sender)
{
    try{
        if( (CbDocument->ItemIndex == -1) ||
            edPage->IsEmpty() ||
            (edPage->Valeur < edPage->Min)||
            (edPage->Valeur > edPage->Max)  ) return;
        if( edPage->Tag != edPage->Valeur)
        {
            AffichePage( ImVisu->Picture->Bitmap->Canvas, edPage->Valeur, edPage->Valeur, true);
            edPage->Tag = edPage->Valeur;
        }
    }CATCH_EXCEPTION( TAG(16))
}
//---------------------------------------------------------------------------

void __fastcall TFrmVisualise::cbZoomChange(TObject *Sender)
{
    if( !ImVisu->Picture->Graphic) return;
    try{
        Glob->ResolutionX = ::MulDiv( Screen->PixelsPerInch, (int)cbZoom->Items->Objects[ cbZoom->ItemIndex] , 100);
        Glob->ResolutionY = Glob->ResolutionX;
        StVisu->Panels->Items[1]->Text = AnsiString(Glob->ResolutionX) + " dpi";
        edPage->Tag = 0;
        edPageChange( NULL);
//        AffichePage( ImVisu->Picture->Bitmap->Canvas, edPage->Valeur, edPage->Valeur, true);
    }CATCH_EXCEPTION( TAG( 17))
}
//---------------------------------------------------------------------------

void __fastcall TFrmVisualise::ActUpdate(TObject *Sender)
{
    try{
        TAction *Act = ((TAction *)Sender);
        if( LstAct->Tag) Act->Enabled = false;
        if( m_PDFInactif && (ActPdf == Act))
          ActPdf->Enabled = false;
        else if( !CbDocument->Items->Count && (Act != ActQuitter) )
            Act->Enabled = false;
        else{
            if( Act->Category == "FirstDoc")   Act->Enabled = CbDocument->ItemIndex;
            else if( Act->Category == "LastDoc")    Act->Enabled = CbDocument->ItemIndex != CbDocument->Items->Count -1;
            else if( Act->Category == "PagePrec")   Act->Enabled = edPage->Valeur != 1;
            else if( Act->Category == "PageSuiv")   Act->Enabled = edPage->Valeur != edPage->Max;
            else if( Act == ActGED)                 Act->Enabled = m_bGEDEICInstalle;
            else if( Act != ActGED)                 Act->Enabled = true;
        }

    } CATCH_EXCEPTION( TAG(18))

}
//---------------------------------------------------------------------------

void __fastcall TFrmVisualise::ActPagePrecExecute(TObject *Sender)
{ 
    try{
    edPage->Valeur--;
    }CATCH_EXCEPTION( TAG(19))
}
//---------------------------------------------------------------------------

void __fastcall TFrmVisualise::ActPageSuivExecute(TObject *Sender)
{
    try{
    edPage->Valeur++;
    }CATCH_EXCEPTION( TAG(20))
}
//---------------------------------------------------------------------------

void __fastcall TFrmVisualise::ActPageDebExecute(TObject *Sender)
{
    try{
    edPage->Valeur = 1;
    }CATCH_EXCEPTION( TAG(21))
}
//---------------------------------------------------------------------------

void __fastcall TFrmVisualise::ActPageEndExecute(TObject *Sender)
{
    try{
/*        CARAC_DOCUMENT* CaracDoc = (CARAC_DOCUMENT*)CbDocument->Items->Objects[ CbDocument->ItemIndex];
        if( !CaracDoc->Etat->NumberOfPage)
        {
            CaracDoc->Etat->CalculNbPages();
            edPage->Max = CaracDoc->Etat->NumberOfPage;
        }*/
        edPage->Valeur = edPage->Max;
    }CATCH_EXCEPTION( TAG(22))
}
//---------------------------------------------------------------------------

void __fastcall TFrmVisualise::ActQuitterExecute(TObject *Sender)
{
    try{
    Close();
    }CATCH_EXCEPTION( TAG(23))
}
//---------------------------------------------------------------------------
void __fastcall TFrmVisualise::InitPage( const TEtat* Etat)
{
    if( (ImVisu->Picture->Graphic->Width != Etat->Largeur.PixelsX) ||
        (ImVisu->Picture->Graphic->Height != Etat->Hauteur.PixelsY)  )
    {
        int r = 0;
        if( m_OldResol)
        {
            r = MAKELONG( Glob->ResolutionX, Glob->ResolutionY);
            Glob->ResolutionX = LOWORD( m_OldResol);
            Glob->ResolutionY = HIWORD( m_OldResol);
        }

        ScbVisu->VertScrollBar->Position = 0;
        ScbVisu->HorzScrollBar->Position = 0;
        ImVisu->Picture->Graphic->Width = Etat->Largeur.PixelsX;
        ImVisu->Picture->Graphic->Height = Etat->Hauteur.PixelsY;
        ImVisu->Width  = ImVisu->Picture->Graphic->Width;
        ImVisu->Height = ImVisu->Picture->Graphic->Height;
        FormResize( NULL);
        if( m_OldResol)
        {
            Glob->ResolutionX = LOWORD( r);
            Glob->ResolutionY = HIWORD( r);
        }
        //::_SelectClipRgn( TAGL, ImVisu->Picture->Bitmap->Canvas->Handle, NULL);
        //Etat->ValidateAll();
        Etat->DocOwner->ChangeSupport( ImVisu->Picture->Bitmap->Canvas, true);

    }
    ScbVisu->VertScrollBar->Position = 0;
    ImVisu->Picture->Bitmap->Canvas->Brush->Color = clWhite;
    ImVisu->Picture->Bitmap->Canvas->Brush->Style = bsSolid;
    ImVisu->Picture->Bitmap->Canvas->FillRect( TRect( 0,0, ImVisu->Picture->Bitmap->Width,
                                                           ImVisu->Picture->Bitmap->Height));
}

void __fastcall TFrmVisualise::AffichePage( TCanvas *canvas, int nFirstPage, int nLastPage, bool bRefresh, MyCBarre *Bar)
{
//MyCBarre b( "Affiche Page", false);
    try{
        bool b;
        StVisu->Panels->Items[0]->Text = "Affichage de la page en cours";
        if( CbDocument->ItemIndex == -1) CbDocument->ItemIndex = 0;
        CARAC_DOCUMENT* CaracDoc = (CARAC_DOCUMENT*)CbDocument->Items->Objects[ CbDocument->ItemIndex];

        int nNbPages = CaracDoc->LstOfPages->Count;
        if( Glob->LanceEnConception)
            CaracDoc->Etat->DocOwner->Langue = edLangue->Position;
        //
/*        if( e->Etat->NumeroEnVisu < m_LstDocument->Count -1)
        {
            ETAT *e1 = (ETAT*)m_LstDocument->Items[ e->Etat->NumeroEnVisu+1];
            while( (e1->Etat->DebPage == Deb_SuitePrec) && (e1->Etat->NumeroEnVisu < m_LstDocument->Count -1)){
                nNbPages += e1->LstOfPages->Count;
                e1 = (ETAT*)m_LstDocument->Items[ e1->Etat->NumeroEnVisu+1];
            }
        }*/
        int nFirstPageToCall = ((nFirstPage < nNbPages)?  nFirstPage : nNbPages);
        CaracDoc->Etat->InitPrinter( Bar);
        CaracDoc->Etat->Nettoie();

//        e->Etat->DocOwner->Selectionne(e->Etat);

  /*      if( bRefresh)
            InitPage(CaracDoc->Etat);*/
        try{
            if( nFirstPageToCall)
            {
                int nNiveau;
                TEtat *e;
                PAGE *p = (PAGE*)CaracDoc->LstOfPages->Items[ nFirstPageToCall-1],
                     *pADessiner = p->GetPageAAfficher( &nNiveau, e);
    /*            for( int i = 0; i < e->Etat->LstCpColonne->Count; i++)
                    ((TCpChamp*)e->Etat->LstCpColonne->Items[i])->Texte = p->LstCpCalcCol->Strings[i];
                for( int i = 0; i < e->Etat->LstCpExtensibles->Count; i++)
                    ((TCpTexte*)e->Etat->LstCpExtensibles->Items[i])->nLastCharPrint = (int)p->LstCpExtensibles->Items[i];*/
                if( !e) e = CaracDoc->Etat;
                e->NiveauTypeBeforeUtil = pADessiner->NiveauTypeBandeAvUtil;
                e->NiveauTypeAfterUtil = pADessiner->NiveauTypeBandeApUtil;
                b = CaracDoc->Etat->DrawPages( ImVisu->Picture->Bitmap->Canvas, p->Bookmark,
                                               nNiveau, pADessiner->wNiveauFirstBande, pADessiner->wTypeFirstBande,
                                               nFirstPageToCall-1, nLastPage - nFirstPageToCall+1, pADessiner->IndiceRepetitionBande);
            }
            else
                b = CaracDoc->Etat->DrawPages( ImVisu->Picture->Bitmap->Canvas, NULL,
                                               0, 0, 0, nFirstPageToCall, nFirstPage - nFirstPageToCall, 0);
        }catch(EAnnulationImpression &e)
        {
            if( !IsPrinting())
            {
                m_bAnnulee = true;
                Close();
                return;
            }
            b = true;
        }
        if( !b)
        {
            int n = CbDocument->ItemIndex;
            FreeAllPages( CbDocument->ItemIndex );
/*            CaracDoc->Etat->UnInitialize();
            delete CaracDoc;
            CbDocument->Items->Delete( CbDocument->ItemIndex);*/
            if( !CbDocument->Items->Count)
            {
                m_bAnnulee = true;
                Close();
            }else
            {
                TEtat *e;
                CbDocument->ItemIndex = max( 0, n-1);
                for( int i = CbDocument->Items->Count-1; i >= CbDocument->ItemIndex; i--)
                {
                    CaracDoc = (CARAC_DOCUMENT*)CbDocument->Items->Objects[ i];
                    CaracDoc->Etat->NumeroEnVisu--;
                    for( TEtat* e = CaracDoc->Etat->EtatSuivant; e != NULL; e = e->EtatSuivant)
                        e->NumeroEnVisu = CaracDoc->Etat->NumeroEnVisu;
                }
                AffichePage( canvas, nFirstPage, nLastPage, bRefresh);
            }
            return;
        }
        if( CaracDoc->Etat->NumberOfPage)
        {
            edPage->Max = CaracDoc->Etat->NumberOfPage;
            if( edPage->Valeur > CaracDoc->Etat->NumberOfPage)
                edPage->Valeur = CaracDoc->Etat->NumberOfPage;
        }else
            edPage->Max = 9999;//CaracDoc->Etat->CurrentPage;
        CaracDoc->Etat->ReleasePrinter();
    }catch( ETropDeColonnes &e)
    {
        ShowMessage( e.Message);
        m_bAnnulee = true;
        Close();
    }
    CATCH_EXCEPTION( TAG( 24))
    StVisu->Panels->Items[0]->Text = EmptyStr;
}

//---------------------------------------------------------------------------
bool __fastcall TFrmVisualise::DebutCaptureGED(Variant *pvGedEIC, const WideString &Classement, bool bSansClassementGED, int &DestGED, const AnsiString &NomDocument)
{
  if( (IsPrinting() && Glob->EICPrinter->Printing) || bSansClassementGED) return true;
  AnsiString NomImprimante;

  if( ::GED_DebutDocument( pvGedEIC, Classement, DestGED, NomDocument, NomImprimante))
    return NomImprimante.IsEmpty() || TEICPrinter::SelectPrinter( NomImprimante);
  return false;
}

void __fastcall TFrmVisualise::ActImprimerExecute(TObject *Sender)
{
    if( !Printer()->Printers->Count)
    {
      ShowMessage( "Aucune imprimante est installée sur ce poste. Vous ne pouvez pas imprimer.");
      return;
    }
    if( IsPrinting()) return;
    MyCBarre *Barre = NULL;
    TSelPrinter *PrintDlg1 = NULL;
    long ligne = __LINE__;
    bool bGED = (Sender == ActGED), bCaptureGED = false;
    bool bPDF = false;
    int PrinterIndexBefore = Printer()->PrinterIndex;
    Variant vGedEIC = Unassigned;
    bool bSansClassementGED = true, bRectoVerso = false;
    try{
        int NbCopies = 1;
        CARAC_DOCUMENT* CaracDoc = NULL;
        int DestGED = 0;
        PrintDlg1 = new TSelPrinter( this);
        if( Visible)
        {
            PrintDlg1->Options << poPageNums << poSelection;
            CaracDoc = (CARAC_DOCUMENT*)CbDocument->Items->Objects[ CbDocument->ItemIndex];
            PrintDlg1->DocName = CbDocument->Text;
            PrintDlg1->MinPage = 1;
            PrintDlg1->MaxPage = edPage->Max;
        }else
        {
            CaracDoc = (CARAC_DOCUMENT*)CbDocument->Items->Objects[ 0];
            PrintDlg1->PrintRange = PrintDialog1->PrintRange;
            PrintDlg1->FromPage   = PrintDialog1->FromPage;
            PrintDlg1->ToPage     = PrintDialog1->ToPage;
        }
        if( fParamVisu) fParamVisu( NbCopies);
        PrintDlg1->Copies = NbCopies;
        PrintDlg1->CopiesShow = m_ShowNbCopies;
        //PrintDlg1->btnGED->Enabled = true;
        //ShowMessage((AnsiString)"Nom De Fichier : "+CaracDoc->Doc->File);
        if (CaracDoc && CaracDoc->Etat)
            bPDF = CaracDoc->Etat->VersPDF;
        if (bPDF) {
            // Le modèle paramétré prévoi l'envoi des impressions vers un PDF
            PrintDlg1->btnGED->NumGlyphs = 1;
            ilFichierEnable->GetBitmap(12,PrintDlg1->btnGED->Glyph);
            PrintDlg1->btnGED->Caption = "Vers PDF";
            PrintDlg1->btnGED->Enabled = true;
            PrintDlg1->btnGED->Visible = true;
        }
        if( !Sender || bGED || (PrintDlg1->ShowModal() != mrCancel))
        {
            if( Sender && !bGED && PrintDlg1->ModalResult == mrYes ) {
                if (!bPDF) bGED = true;
            } else {
                bPDF = false;
            }

            if (bPDF) {
                // On lance la génération du PDF
                SaveDialog1->FileName = CaracDoc->Etat->GED_Criteres;
                ActPdfExecute(NULL);
                // On quitte
                goto finally;
            }

            if( bGED)
            {
              AnsiString NomImprimante;
              bSansClassementGED = !GED_IsClassAuto();
              if( GED_Ouvre( &vGedEIC))
              {
                if( bSansClassementGED)
                {
                  if( GED_Envoi( &vGedEIC, EmptyStr, EmptyStr, DestGED, NomImprimante) != mrOk)
                    goto finally;
                  if( !TEICPrinter::SelectPrinter( NomImprimante))
                    goto finally;
                }
              }
              else
                  goto finally;
            }
            PrintDialog1->PrintRange = PrintDlg1->PrintRange;
            PrintDialog1->FromPage   = PrintDlg1->FromPage;
            PrintDialog1->ToPage     = PrintDlg1->ToPage;
            StVisu->Panels->Items[0]->Text = "Impression en cours";
TRACEF( TAGL, "Début de l'impression");
            Glob->EICPrinter = new TEICPrinter( PT_Standard);
            Glob->EICPrinter->Zoom = PrintDlg1->edZoom->Valeur;
            Glob->EICPrinter->PaysagePortraitAssembles = PrintDlg1->cbPaysagePortraitAssembles->Checked;
            {
                char     ADevice[225], ADriver[225], APort[225];
                DEVMODE *pDevMode = 0;
                HGLOBAL  hDeviceMode = 0;

                Printer()->GetPrinter( ADevice, ADriver, APort, (UINT)hDeviceMode);
                pDevMode = (DEVMODE*)::_GlobalLock( TAGL, (HGLOBAL)hDeviceMode);
                bRectoVerso = (pDevMode->dmFields & DM_DUPLEX) && (pDevMode->dmDuplex != DMDUP_SIMPLEX);
                if( !Visible)
                {
                  pDevMode->dmCollate = true;
                  Printer()->SetPrinter( ADevice, ADriver, APort, (UINT)hDeviceMode);
                }
                ::_GlobalUnlock( TAGL, (HGLOBAL)hDeviceMode); pDevMode = NULL;
            }
ligne = __LINE__;
//            EICPrinter->BeginDoc();
            switch( PrintDlg1->PrintRange)
            {
                case prAllPages :
                {
ligne = __LINE__;
                        try{ Barre = new MyCBarre("Impression en cours"); }catch(...){}
ligne = __LINE__;
                        if( Barre)
                        {
                            Barre->DoubleAffichage = true;
                            Barre->Max = CbDocument->Items->Count;
                        }
ligne = __LINE__;
                        AnsiString GED_CriteresPrec, NomDocGEDPrec;
                        bool bDebutCaptureGED = false;
                        for( int i = 0; i < CbDocument->Items->Count; i++)
                        {
                            if( Barre) Barre->MessageInfo = CbDocument->Items->Strings[i];
                            CARAC_DOCUMENT* CaracDoc = (CARAC_DOCUMENT*)CbDocument->Items->Objects[ i];
                            if( m_ShowNbCopies)
                                CaracDoc->Etat->NbCopies = PrintDlg1->Copies;
ligne = __LINE__;
                            if( bGED && ((CaracDoc->Etat->GED_Criteres != GED_CriteresPrec)|| (CaracDoc->Etat->NomDocGED != NomDocGEDPrec)) )
                              bDebutCaptureGED = DebutCaptureGED( &vGedEIC, CaracDoc->Etat->GED_Criteres, bSansClassementGED, DestGED, CaracDoc->Etat->NomDocGED);
                            if( !bGED || bDebutCaptureGED)
                            {
                              bCaptureGED = bGED;
                              CaracDoc->Etat->InitPrinter( Barre);
                              CaracDoc->Etat->Nettoie();
ligne = __LINE__;
                              if( CaracDoc->Etat->LstCpExtensibles)
                                  for( int j = 0; j < CaracDoc->Etat->LstCpExtensibles->Count; j++)
                                      ((TCpTexte*)CaracDoc->Etat->LstCpExtensibles->Items[j])->nLastCharPrint = -1;
                              if( CaracDoc->Etat->LstCpEnCours)
                                  CaracDoc->Etat->LstCpEnCours->Clear();
ligne = __LINE__;
                              CaracDoc->Etat->DocOwner->Draw( Glob->EICPrinter->Canvas, CaracDoc->Etat);

                              if( (i > NB_DOC_MAX_SANS_FERMER) && (i != CbDocument->ItemIndex))
                              {
                                for( TEtat *Etat = CaracDoc->Etat; Etat; Etat = Etat->EtatSuivant)
                                {
                                    if( Etat->BaseDeDonnee) Etat->BaseDeDonnee->Close();
                                }
                              }
ligne = __LINE__;
                              CaracDoc->Etat->ReleasePrinter();
ligne = __LINE__;
                              if( IsPrinting() && Glob->EICPrinter->Printing)
                              {
                                  bool bStopDoc = false;
                                  if( bGED || !GetModuleHandle( "CoEtats.dll"))
                                  {
                                    if( i < CbDocument->Items->Count-1)
                                    {
                                      CARAC_DOCUMENT* CaracDocSuiv = (CARAC_DOCUMENT*)CbDocument->Items->Objects[ i+1];
                                      bStopDoc = (CaracDocSuiv->Etat->GED_Criteres != CaracDoc->Etat->GED_Criteres) ||
                                                    (CaracDocSuiv->Etat->NomDocGED != CaracDoc->Etat->NomDocGED) ||
                                                    (!bGED && (CaracDoc->Etat->DebPage == Deb_AutreDocument) && bRectoVerso);
                                    }else
                                      bStopDoc = true;
                                  }
                                  if( /*!bGED ||*/ bStopDoc)
                                  {
                                    if( CaracDoc->Etat->NbCopies)
                                      Glob->EICPrinter->EndDoc();
                                    else
                                      Glob->EICPrinter->Abort();
                                  }
                              }
                            }
                            if( bGED && !bSansClassementGED && (!IsPrinting() || !Glob->EICPrinter->Printing))
                            {
                                ::GED_FinDocument( &vGedEIC);
                                bCaptureGED = false;
                            }
                            if( Barre)Barre->Position++;
                            GED_CriteresPrec = CaracDoc->Etat->GED_Criteres;
                            NomDocGEDPrec    = CaracDoc->Etat->NomDocGED;
ligne = __LINE__;
                        }
//Barre n'est pas remis à NULL, ce qui fait planter le delete suivant                        if( Barre) delete Barre;
ligne = __LINE__;
                    }
                    break;
                case prSelection :
ligne = __LINE__;
                        if( m_ShowNbCopies)
                            CaracDoc->Etat->NbCopies = PrintDlg1->Copies;
ligne = __LINE__;
                        if( !bGED || DebutCaptureGED( &vGedEIC, CLASSEMENT_NON_REMPLI, bSansClassementGED, DestGED, CaracDoc->Etat->NomDocGED))
                        {
                          bCaptureGED = bGED;
                          AffichePage( Glob->EICPrinter->Canvas, edPage->Valeur, edPage->Valeur);
                        }
ligne = __LINE__;
                    break;
                case prPageNums :
                    {   bool bPrintOnlyBefore = m_bPrintOnly;
                        m_bPrintOnly = false;

ligne = __LINE__;
                        try{ Barre = new MyCBarre("Impression en cours"); }catch(...){}
ligne = __LINE__;

                        if( m_ShowNbCopies)
                            CaracDoc->Etat->NbCopies = PrintDlg1->Copies;
//                        Barre->Max = 0;
//                        Barre->DoubleAffichage = false;
                        try{
                          if( !bGED || DebutCaptureGED( &vGedEIC, CLASSEMENT_NON_REMPLI, bSansClassementGED, DestGED, CaracDoc->Etat->NomDocGED))
                          {
                            bCaptureGED = bGED;
                            CaracDoc->Etat->DocOwner->EtatEnCours = CaracDoc->Etat;
                            CaracDoc->Etat->Initialize();  //permet le calcul du nb de page
                            CaracDoc->Etat->DocOwner->EtatEnCours = NULL;
ligne = __LINE__;
                            AffichePage( Glob->EICPrinter->Canvas, PrintDlg1->FromPage, PrintDlg1->ToPage, false, Barre);

ligne = __LINE__;         }
                        }catch( EAnnulationImpression &e){}
//Barre n'est pas remis à NULL, ce qui fait planter le delete suivant                        if( Barre) delete Barre;
                        m_bPrintOnly = bPrintOnlyBefore;
                    }break;
            }

TRACEF( TAGL, "Fin de l'impression");
            m_ImpressionFaite = true;
        }
finally:
    }CATCH_EXCEPTIONc( TAG( 25), {TRACEF(TAGL, "Ligne de l'erreur :"+ligne);});

    if( IsPrinting() && Glob->EICPrinter->Printing)
      Glob->EICPrinter->EndDoc();
    delete Glob->EICPrinter; Glob->EICPrinter = NULL;
    StVisu->Panels->Items[0]->Text = "";
    if( Barre) delete Barre;

    if( bGED)
    {
      if( !vGedEIC.IsNull())
      {
        if( bCaptureGED) ::GED_FinDocument( &vGedEIC);
        GED_Ferme( &vGedEIC);
      }
      Printer()->PrinterIndex = PrinterIndexBefore;
    }
    SetCurrentDir( Glob->CurrentDir);
    delete PrintDlg1;
}
//---------------------------------------------------------------------------

void __fastcall TFrmVisualise::ActDocPrecExecute(TObject *Sender)
{
    try{
        CbDocument->ItemIndex--;
        CbDocumentChange( NULL);
    }CATCH_EXCEPTION( TAG(26))
}
//---------------------------------------------------------------------------

void __fastcall TFrmVisualise::ActDocSuivExecute(TObject *Sender)
{
    try{
        CbDocument->ItemIndex++;
        CbDocumentChange( NULL);
    }CATCH_EXCEPTION( TAG(27))
}
//---------------------------------------------------------------------------

void __fastcall TFrmVisualise::PrintDialog1Show(TObject *Sender)
{
/*    try{
        RECT rc;
        ::SetWindowText( ::GetDlgItem( PrintDialog1->Handle, 0x421), "Page c&ourante");

        ::GetClientRect( ::GetDlgItem( PrintDialog1->Handle, 0x420), &rc);
        ::SetWindowPos( ::GetDlgItem( PrintDialog1->Handle, 0x420), NULL,
                        0, 0, rc.right-rc.left + 100, rc.bottom-rc.top,
                        SWP_NOMOVE | SWP_NOREPOSITION |SWP_NOZORDER);
        if( !m_ShowNbCopies)
        {
            ::EnableWindow( ::GetDlgItem( PrintDialog1->Handle, 0x0431), FALSE);
            ::EnableWindow( ::GetDlgItem( PrintDialog1->Handle, 0x0444), FALSE);
            ::EnableWindow( ::GetDlgItem( PrintDialog1->Handle, 0x0482), FALSE);
            ::EnableWindow( ::GetDlgItem( PrintDialog1->Handle, 0x270f), FALSE);
        }
    }CATCH_EXCEPTION( TAG(28))*/
}
//---------------------------------------------------------------------------


//#define _TEST
void __fastcall TFrmVisualise::ActPdfExecute(TObject *Sender)
{
    if( IsPrinting()) return;
    int AncResolEcranX = Glob->ResolutionX,
        AncResolEcranY = Glob->ResolutionY;
    try{

        bool bSaveDialog = Sender && SaveDialog1->FileName.IsEmpty();
        char* szFileCharInvalids ="\\/:*?\"<>|";
        CARAC_DOCUMENT* CaracDoc;
        MyCBarre *Barre = NULL;
        if( bSaveDialog)
        {
            AnsiString s = Caption + ".pdf";
            for( int i=1; i <= s.Length(); i++)
            {
                if( strchr( szFileCharInvalids, s[i])) s[i] = '_';
            }
            SaveDialog1->FileName = s;
        }
        if( !bSaveDialog || SaveDialog1->Execute())
        {
            try{ try{
                HANDLE hFile = CreateFile( SaveDialog1->FileName.c_str(), GENERIC_READ	| GENERIC_WRITE, 0, NULL, OPEN_ALWAYS, 0, 0);
                if( hFile != INVALID_HANDLE_VALUE)
                {
                    CloseHandle( hFile);
                    PrintDialog1->PrintRange = prAllPages;
                    Glob->EICPrinter = new TEICPrinter( PT_PDF, SaveDialog1->FileName, !bSaveDialog);
                    StVisu->Panels->Items[0]->Text = "Génération PDF en cours";
                    try{
                        Barre = new MyCBarre("Génération PDF en cours");
                        Barre->DoubleAffichage = true;
                        Barre->Max = CbDocument->Items->Count;
                    }catch(...){}
                    for( int i = 0; i < CbDocument->Items->Count; i++)
                    {
                        CaracDoc = (CARAC_DOCUMENT*)CbDocument->Items->Objects[ i];
                        CaracDoc->Etat->InitPrinter( Barre);
                        CaracDoc->Etat->Nettoie();
                        if( CaracDoc->Etat->LstCpExtensibles)
                            for( int j = 0; j < CaracDoc->Etat->LstCpExtensibles->Count; j++)
                                ((TCpTexte*)CaracDoc->Etat->LstCpExtensibles->Items[j])->nLastCharPrint = -1;
                        if( CaracDoc->Etat->LstCpEnCours)
                            CaracDoc->Etat->LstCpEnCours->Clear();
                        CaracDoc->Etat->DocOwner->Draw( Glob->EICPrinter->Canvas, CaracDoc->Etat);
                        CaracDoc->Etat->ReleasePrinter();
                        if( Barre) Barre->Position++;
                    }
                }else
                    ShowMessage( "Vous n'avez pas les droits suffisants pour écrire dans ce répertoire.\r\n" 
                                 "Veuillez contacter votre administreur réseau ou choisir un autre répertoire de destination.");
                m_ImpressionFaite = true;
            }catch( EAbort &ex) {}
            CATCH_EXCEPTION( TAG( 29))
            }__finally
            {
                if( Barre) delete Barre;
                if( Glob->EICPrinter)
                {
                    if( Glob->EICPrinter->Printing) Glob->EICPrinter->EndDoc();
                    delete Glob->EICPrinter; Glob->EICPrinter = NULL;
                }
                StVisu->Panels->Items[0]->Text = "";
            }
        }
    }CATCH_EXCEPTION( TAG(30))
    SaveDialog1->FileName = EmptyStr;

    Glob->ResolutionX = AncResolEcranX;
    Glob->ResolutionY = AncResolEcranY;
}
//---------------------------------------------------------------------------

void __fastcall TFrmVisualise::FormKeyDown(TObject *Sender, WORD &Key,
      TShiftState Shift)
{
#define PAS 10
    try{
        bool bHorz = true;
        if( AnsiString(Sender->ClassName()) == "CEditNum") bHorz = false;
        if( Shift == TShiftState())
        {
            switch( Key)
            {
                case VK_UP:    ScbVisu->VertScrollBar->Position -= PAS; break;
                case VK_DOWN:  ScbVisu->VertScrollBar->Position += PAS; break;
                case VK_LEFT:  if( bHorz) ScbVisu->HorzScrollBar->Position -= PAS; break;
                case VK_RIGHT: if( bHorz) ScbVisu->HorzScrollBar->Position += PAS; break;
                case VK_END:   ScbVisu->VertScrollBar->Position = ScbVisu->VertScrollBar->Range; break;
                case VK_HOME:  ScbVisu->VertScrollBar->Position = 0;    break;
                case VK_PRIOR: ActDocPrec->Execute(); break;
                case VK_NEXT:  ActDocSuiv->Execute(); break;
            }
        }
    }CATCH_EXCEPTION( TAG(31))
}
//---------------------------------------------------------------------------

void __fastcall TFrmVisualise::ActHelpExecute(TObject *Sender)
{
    try{
        EditAboutBox( this, "Etat.dll");
    }CATCH_EXCEPTION( TAG(32))
}
//---------------------------------------------------------------------------





void __fastcall TFrmVisualise::ActMailExecute(TObject *Sender)
{
//
}
//---------------------------------------------------------------------------


void __fastcall TFrmVisualise::LstActExecute(TBasicAction *Action,
      bool &Handled)
{
    if( !Action->Tag)
    {
        if( !LstAct->Tag)
        {
            LstAct->Tag = 1;
            Action->Tag = 1;
                Action->Execute();
            Action->Tag = 0;
            LstAct->Tag = 0;
        }
        Handled = true;
    }
}
//---------------------------------------------------------------------------

void __fastcall TFrmVisualise::edLangueChange(TObject *Sender)
{
    AffichePage( ImVisu->Picture->Bitmap->Canvas, edPage->Valeur, edPage->Valeur, true);
}
//---------------------------------------------------------------------------

void __fastcall TFrmVisualise::FormClose(TObject *Sender,
      TCloseAction &Action)
{
    if( Action == caFree)
    {
        CbDocument->WindowProc = m_OldWindowProcCbDocument;
        cbZoom->WindowProc = m_OldWindowProccbZoom;
        FreeAllPages();
    }
}
//---------------------------------------------------------------------------

void __fastcall TFrmVisualise::ActParametrageExecute(TObject *Sender)
{
    TfrmParametrages *frmParametrages = new TfrmParametrages( NULL);
    frmParametrages->ShowModal();
    delete frmParametrages;
}
//---------------------------------------------------------------------------


void __fastcall TFrmVisualise::FormMouseWheel(TObject *Sender,
      TShiftState Shift, int WheelDelta, TPoint &MousePos, bool &Handled)
{
  TPoint MosePoscl = ScreenToClient( MousePos);
  if( ControlAtPos( MosePoscl, true, true) == ScbVisu)
    ScbVisu->VertScrollBar->Position -= WheelDelta;
  Handled = true;
//
}
//---------------------------------------------------------------------------

void __fastcall TFrmVisualise::ScbVisuMouseDown(TObject *Sender,
      TMouseButton Button, TShiftState Shift, int X, int Y)
{
    m_Drag.y = Y;
    m_Drag.x = X;
}
//---------------------------------------------------------------------------

void __fastcall TFrmVisualise::ScbVisuMouseMove(TObject *Sender,
      TShiftState Shift, int X, int Y)
{
  if( (m_Drag.y != -1) && (m_Drag.x != -1))
  {
    ScbVisu->VertScrollBar->Position += m_Drag.y - Y;
    ScbVisu->HorzScrollBar->Position += m_Drag.x - X;
    m_Drag.y = Y;
    m_Drag.x = X;
  }
}
//---------------------------------------------------------------------------

void __fastcall TFrmVisualise::ScbVisuMouseUp(TObject *Sender,
      TMouseButton Button, TShiftState Shift, int X, int Y)
{
    m_Drag.y = -1;
    m_Drag.x = -1;
}
//---------------------------------------------------------------------------


void __fastcall TFrmVisualise::ImVisuMouseDown(TObject *Sender,
      TMouseButton Button, TShiftState Shift, int X, int Y)
{
  TPoint p(X, Y);
  p = ScbVisu->ScreenToClient( ImVisu->ClientToScreen(p));
  ScbVisuMouseDown( Sender, Button, Shift, p.x, p.y);
}
//---------------------------------------------------------------------------

void __fastcall TFrmVisualise::ImVisuMouseMove(TObject *Sender,
      TShiftState Shift, int X, int Y)
{
  TPoint p(X, Y);
  p = ScbVisu->ScreenToClient( ImVisu->ClientToScreen(p));
  ScbVisuMouseMove( Sender, Shift, p.x, p.y);
}
//---------------------------------------------------------------------------

void __fastcall TFrmVisualise::ImVisuMouseUp(TObject *Sender,
      TMouseButton Button, TShiftState Shift, int X, int Y)
{
  TPoint p(X, Y);
  p = ScbVisu->ScreenToClient( ImVisu->ClientToScreen(p));
  ScbVisuMouseUp( Sender, Button, Shift, p.x, p.y);
}
//---------------------------------------------------------------------------

void __fastcall TFrmVisualise::FormResize(TObject *Sender)
{
  int ScbVisuWidth = ScbVisu->ClientWidth - (ScbVisu->VertScrollBar->IsScrollBarVisible()? ScbVisu->VertScrollBar->Size:0);
  int ScbVisuHeight = ScbVisu->ClientHeight - (ScbVisu->HorzScrollBar->IsScrollBarVisible()? ScbVisu->HorzScrollBar->Size:0);

  if( ImVisu->Width < ScbVisuWidth)
       ImVisu->Left = (ScbVisuWidth - ImVisu->Width) / 2;
  else ImVisu->Left = 0;
  ImVisu->Left -= (ScbVisu->HorzScrollBar->IsScrollBarVisible()? ScbVisu->HorzScrollBar->Position:0);
  if( ImVisu->Height < ScbVisuHeight)
       ImVisu->Top = (ScbVisuHeight - ImVisu->Height) / 2;
  else ImVisu->Top   = 0;
  ImVisu->Top -= (ScbVisu->VertScrollBar->IsScrollBarVisible()? ScbVisu->VertScrollBar->Position:0);
}
//---------------------------------------------------------------------------

